Lumen & Gesso / website · lumengesso.com / app / api / orders / [id] / cancel / route.ts
| 1 | import { NextResponse, type NextRequest } from 'next/server'; |
| 2 | import { getCustomerUser } from '@/app/lib/lumen-auth'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { stripe } from '@/app/lib/stripe'; |
| 5 | import { sendEmail } from '@/app/lib/email'; |
| 6 | import { env } from '@/app/lib/env'; |
| 7 | import { displayOrderId } from '@/app/lib/orders'; |
| 8 | import { cancellationCustomerHtml, cancellationNoPaymentHtml, cancellationStudioHtml, cancellationStudioInternalHtml } from '@/app/lib/order-emails'; |
| 9 | |
| 10 | export const runtime = 'nodejs'; |
| 11 | export const dynamic = 'force-dynamic'; |
| 12 | |
| 13 | // Cancel an order any time before the customer approves their proof (and |
| 14 | // we send it to print). If a payment is on file we issue a full Stripe |
| 15 | // refund; if there's NO payment (the order never completed checkout, or |
| 16 | // no payment intent was recorded) we still force-cancel it — the customer |
| 17 | // doesn't have to do anything — and tell them no payment was found and to |
| 18 | // contact the studio if that's wrong. This matches the Refund policy |
| 19 | // ("fully refundable before you approve"): a customer can self-cancel |
| 20 | // while the order is in the design queue (pending_design) or while a |
| 21 | // proof is awaiting their approval (awaiting_approval). Once approved / |
| 22 | // in production, cancellation needs different handling and isn't allowed |
| 23 | // here. |
| 24 | const CANCELLABLE_STATUSES = ['pending_design', 'awaiting_approval', 'revision_requested']; |
| 25 | |
| 26 | export async function POST( |
| 27 | req: NextRequest, |
| 28 | ctx: { params: Promise<{ id: string }> }, |
| 29 | ) { |
| 30 | const { id } = await ctx.params; |
| 31 | |
| 32 | const user = await getCustomerUser(); |
| 33 | if (!user) { |
| 34 | return NextResponse.json({ error: 'You must be signed in to cancel an order.' }, { status: 401 }); |
| 35 | } |
| 36 | |
| 37 | const admin = commerceDb(); |
| 38 | const { data: order, error: fetchErr } = await admin |
| 39 | .from('orders') |
| 40 | .select('id, user_id, user_email, status, price_cents, stripe_payment_intent_id, config, updated_at') |
| 41 | .eq('id', id) |
| 42 | .single(); |
| 43 | |
| 44 | if (fetchErr || !order) { |
| 45 | return NextResponse.json({ error: 'Order not found.' }, { status: 404 }); |
| 46 | } |
| 47 | if (order.user_id !== user.id) { |
| 48 | return NextResponse.json({ error: 'You can only cancel your own orders.' }, { status: 403 }); |
| 49 | } |
| 50 | const config = (order.config ?? {}) as Record<string, unknown>; |
| 51 | const previousCancellation = config.customerCancellation as { state?: 'pending' | 'refunded' | 'unpaid' } | undefined; |
| 52 | const retry = order.status === 'cancelled' && previousCancellation?.state === 'pending'; |
| 53 | if (order.status === 'cancelled' && previousCancellation && !retry) { |
| 54 | return NextResponse.json({ ok: true, noPayment: previousCancellation.state === 'unpaid' }); |
| 55 | } |
| 56 | if (!retry && !CANCELLABLE_STATUSES.includes(order.status)) { |
| 57 | return NextResponse.json({ |
| 58 | error: `This order can no longer be cancelled — it's already past the design queue. Reach out at hello@lumengesso.com if something's wrong.`, |
| 59 | }, { status: 409 }); |
| 60 | } |
| 61 | if (!retry) { |
| 62 | // Claim cancellation before touching Stripe. Approval and cancellation |
| 63 | // both compare the status, so only one can win. |
| 64 | const { data: claimed, error } = await admin.from('orders') |
| 65 | .update({ status: 'cancelled', config: { ...config, customerCancellation: { state: 'pending' } } }) |
| 66 | .eq('id', id).eq('user_id', user.id).eq('status', order.status).eq('updated_at', order.updated_at) |
| 67 | .select('id').maybeSingle(); |
| 68 | if (error || !claimed) { |
| 69 | return NextResponse.json({ error: 'The order changed. Reload the order before trying again.' }, { status: error ? 500 : 409 }); |
| 70 | } |
| 71 | } |
| 72 | // If a payment is on file, issue a full refund. If there's NO payment |
| 73 | // intent, skip the refund and force-cancel. We never surface raw Stripe |
| 74 | // error text to the customer. |
| 75 | let refundId: string | null = null; |
| 76 | let alreadyRefunded = false; |
| 77 | if (order.stripe_payment_intent_id) { |
| 78 | try { |
| 79 | const refund = await stripe().refunds.create({ |
| 80 | payment_intent: order.stripe_payment_intent_id, |
| 81 | reason: 'requested_by_customer', |
| 82 | metadata: { orderId: order.id, source: 'customer-self-cancel' }, |
| 83 | }, { idempotencyKey: `customer-cancellation:${order.id}:${order.stripe_payment_intent_id}` }); |
| 84 | if (refund.status === 'failed' || refund.status === 'canceled') throw new Error('Refund was not accepted'); |
| 85 | refundId = refund.id; |
| 86 | } catch (e) { |
| 87 | const errObj = (e ?? {}) as { code?: unknown; message?: unknown }; |
| 88 | const code = typeof errObj.code === 'string' ? errObj.code : ''; |
| 89 | const emsg = typeof errObj.message === 'string' ? errObj.message : ''; |
| 90 | // The charge was already refunded (e.g. manually from the Stripe |
| 91 | // dashboard). That's the desired end state — treat it as success and |
| 92 | // let the cancel proceed rather than erroring at the customer. |
| 93 | if (code === 'charge_already_refunded' || /already been refunded/i.test(emsg)) { |
| 94 | alreadyRefunded = true; |
| 95 | } else { |
| 96 | console.error('[cancel] Stripe refund failed', e); |
| 97 | // Friendly, non-technical message — no raw Stripe error. |
| 98 | return NextResponse.json({ |
| 99 | error: 'The order is cancelled and your photos are saved, but we could not confirm the refund. Retry from this order or contact hello@lumengesso.com.', |
| 100 | }, { status: 500 }); |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | const refunded = !!refundId || alreadyRefunded; |
| 105 | |
| 106 | // Mark the order cancelled. Status transition is the source of truth; |
| 107 | // refund evidence (if any) lives on Stripe's side via the payment_intent. |
| 108 | const { data: finalized, error: updErr } = await admin.from('orders').update({ |
| 109 | config: { ...config, customerCancellation: { state: refunded ? 'refunded' : 'unpaid' } }, |
| 110 | }).eq('id', id).eq('user_id', user.id).eq('status', 'cancelled').eq('config->customerCancellation->>state', 'pending') |
| 111 | .select('id').maybeSingle(); |
| 112 | |
| 113 | if (updErr) { |
| 114 | console.error('[cancel] DB update failed', updErr); |
| 115 | // If a refund already went out, don't fail the response — the money is |
| 116 | // back and the row will be reconciled. If there was no refund, the |
| 117 | // cancel genuinely didn't persist, so surface the error. |
| 118 | return NextResponse.json({ error: 'The order is cancelled. Reload and retry to confirm the refund status.' }, { status: 500 }); |
| 119 | } |
| 120 | if (!finalized) return NextResponse.json({ ok: true, refundId, noPayment: !refunded }); |
| 121 | |
| 122 | // Best-effort notifications. Don't fail the cancel flow on email errors. |
| 123 | const amount = `$${(order.price_cents / 100).toFixed(2)}`; |
| 124 | await Promise.allSettled([ |
| 125 | sendEmail({ |
| 126 | to: order.user_email, |
| 127 | subject: `Cancellation confirmed — ${displayOrderId(order.id)}`, |
| 128 | html: refunded |
| 129 | ? cancellationCustomerHtml(order.id, order.price_cents) |
| 130 | : cancellationNoPaymentHtml(order.id), |
| 131 | text: refunded |
| 132 | ? `Your commission ${displayOrderId(order.id)} has been cancelled and a full refund of ${amount} has been issued. Funds typically return to your card within 5–10 business days.` |
| 133 | : `Your commission ${displayOrderId(order.id)} has been cancelled. We didn't find a completed payment on this order, so there's nothing to refund — you haven't been charged. If you believe this is an error, contact hello@lumengesso.com.`, |
| 134 | }), |
| 135 | refunded |
| 136 | ? sendEmail({ |
| 137 | to: env.site.studioEmail(), |
| 138 | subject: `Cancelled: ${displayOrderId(order.id)} — ${order.user_email}`, |
| 139 | html: cancellationStudioHtml(order.id, order.user_email, order.price_cents), |
| 140 | text: `Order ${order.id} cancelled by ${order.user_email}. ${refundId ? `Refund ${amount} issued (Stripe id ${refundId}).` : `Charge was already refunded — no new refund issued.`}`, |
| 141 | }) |
| 142 | : sendEmail({ |
| 143 | to: env.site.studioEmail(), |
| 144 | subject: `Cancelled (no payment): ${displayOrderId(order.id)} — ${order.user_email}`, |
| 145 | html: cancellationStudioInternalHtml(order.id, order.user_email, order.price_cents, { |
| 146 | reason: 'Customer self-cancel — no payment on file', |
| 147 | refundId: null, |
| 148 | refundError: null, |
| 149 | prodigiOrderId: null, |
| 150 | }), |
| 151 | text: `Order ${order.id} self-cancelled by ${order.user_email}. No payment on file — cancelled without refund.`, |
| 152 | }), |
| 153 | ]); |
| 154 | |
| 155 | return NextResponse.json({ ok: true, refundId, noPayment: !refunded }); |
| 156 | } |